//
//  LZXHelper.m
//  Connotation
//
//  Created by Xuan on 14-5-20.
//  Copyright (c) 2014年 Xuan. All rights reserved.
//

#import "LZXHelper.h"
//#import "NSString+Hashing.h"
#import <sys/sysctl.h>
#import <mach/mach.h>
#import <Security/Security.h>
#import "SSKeychain.h"
#import "MBProgressHUD.h"
@implementation LZXHelper
+ (NSString *)dateStringFromNumberTimer:(NSString *)timerStr {
    //转化为Double
    double t = [timerStr doubleValue];
    //计算出距离1970的NSDate
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:t];
    //转化为 时间格式化字符串
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    //转化为 时间字符串
    return [df stringFromDate:date];
}
//动态 计算行高
//根据字符串的实际内容的多少 在固定的宽度和字体的大小，动态的计算出实际的高度
+ (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{
    if ([LZXHelper getCurrentIOS] >= 7.0) {
        //iOS7之后
        /*
         第一个参数: 预设空间 宽度固定  高度预设 一个最大值
         第二个参数: 行间距 如果超出范围是否截断
         第三个参数: 属性字典 可以设置字体大小
         */
        NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
        CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
        //返回计算出的行高
        return rect.size.height;
        
    }else {
        //iOS7之前
        /*
         1.第一个参数  设置的字体固定大小
         2.预设 宽度和高度 宽度是固定的 高度一般写成最大值
         3.换行模式 字符换行
         */
        //CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(textWidth, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        NSLog(@"你的版本是6.0以前");
        return 0;//返回 计算出得行高
    }
}
//计算富文本字体高度
/**
 *  计算富文本字体高度
 *
 *  @param lineSpeace 行高
 *  @param font       字体
 *  @param width      字体所占宽度
 *
 *  @return 富文本高度
 */

+ (CGFloat)getAttributedStringHeightwithSpeace:(CGFloat)lineSpeace withFont:(UIFont*)font withWidth:(CGFloat)width attributedString:(NSString *)attributedString{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    //    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    /** 行高 */
    paraStyle.lineSpacing = lineSpeace;
    // NSKernAttributeName字体间距
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          };
    CGSize size = [attributedString boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

+ (CGFloat)textWidthFromTextString:(NSString *)text Height:(CGFloat)textHeight fontSize:(CGFloat)size{
//    if ([LZXHelper getCurrentIOS] >= 7.0) {
        //iOS7之后
        /*
         第一个参数: 预设空间 宽度固定  高度预设 一个最大值
         第二个参数: 行间距 如果超出范围是否截断
         第三个参数: 属性字典 可以设置字体大小
         */
        NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
        CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, textHeight) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
        //返回计算出的行高
        return rect.size.width;
//    }
//    }else {
//        //iOS7之前
//        /*
//         1.第一个参数  设置的字体固定大小
//         2.预设 宽度和高度 宽度是固定的 高度一般写成最大值
//         3.换行模式 字符换行
//         */
//        CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(MAXFLOAT, textHeight) lineBreakMode:NSLineBreakByCharWrapping];
//        return textSize.width;//返回 计算出得行高
//    }

}

//获取iOS版本号
+ (double)getCurrentIOS {
    return [[[UIDevice currentDevice] systemVersion] doubleValue];
}
+ (CGSize)getScreenSize {
    return [[UIScreen mainScreen] bounds].size;
}
//获得当前系统时间到指定时间的时间差字符串,传入目标时间字符串和格式
+(NSString*)stringNowToDate:(NSString*)toDate formater:(NSString*)formatStr
{
    
    NSDateFormatter *formater=[[NSDateFormatter alloc] init];
    if (formatStr) {
        [formater setDateFormat:formatStr];
    }
    else{
        [formater setDateFormat:[NSString stringWithFormat:@"yyyy-MM-dd HH:mm:ss"]];
    }
    NSDate *date=[formater dateFromString:toDate];
    
    return [self stringNowToDate:date];
    
}
//获得到指定时间的时间差字符串,格式在此方法内返回前自己根据需要格式化
+(NSString*)stringNowToDate:(NSDate*)toDate
{
    //创建日期 NSCalendar对象
    NSCalendar *cal = [NSCalendar currentCalendar];
    //得到当前时间
    NSDate *today = [NSDate date];
    
    //用来得到具体的时差,位运算
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
    
    if (toDate && today) {//不为nil进行转化
        NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:toDate options:0 ];
        
        //NSString *dateStr=[NSString stringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day], [d hour], [d minute], [d second]];
        NSString *dateStr=[NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)[d hour], (long)[d minute], (long)[d second]];
        return dateStr;
    }
    return @"";
}

//获取缓存文件 在 沙盒 Library/Caches 中的路径
//url 在函数里面进行 md5 加密处理之后的 作为 缓存文件的文件名

+ (NSString *)getFullCacheFilePathWithUrl:(NSString *)url{
    //1.拼接沙盒缓存路径 MyCaches是我们自己创建一个目录
    NSString * myCachePath = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/MyCaches"];
    NSFileManager *fm = [NSFileManager defaultManager];
    //2.判断自己的缓存目录是否存在
    if (![fm fileExistsAtPath:myCachePath]) {
        //不存在那么就创建一个 MyCaches
        BOOL ret = [fm createDirectoryAtPath:myCachePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (!ret) {
            NSLog(@"缓存目录创建失败");
        }
    }
    //md5 对字符串加密 处理
    //url = [url MD5Hash];
    //拼接问价的全路径
    return [myCachePath stringByAppendingFormat:@"/%@",url];
}
//判断 缓存文件 是否 超时
//url 是一个网址
//一个url 地址 对应一个 缓存文件， 缓存文件名字 用md5对url 进行加密之后命名
+ (BOOL)isOutTimeOfFileWithUrl:(NSString *)url  outTime:(NSTimeInterval)time{
    
    //获取url 对应的缓存文件的地址
    NSString * fileCache = [LZXHelper getFullCacheFilePathWithUrl:url];
    NSFileManager *fm = [NSFileManager defaultManager];
    //获取文件 属性字典
    NSDictionary *dict = [fm attributesOfItemAtPath:fileCache error:nil];
    //获取当前文件的上次修改时间
    NSDate *pastDate = [dict fileModificationDate];
    //时间差 获取上次修改时间和当前时间的时间差  单位s
    NSTimeInterval subTimer = [pastDate timeIntervalSinceNow];
    //一般缓存文件 超时时间 设置为 1小时 60*60s
    //时间差是正的
    if (subTimer < 0) {
        subTimer = - subTimer;
    }
    if (subTimer > time) {//超时 可以设置为 1小时
        return YES;//超时
    }else  {
        return NO;//没有超时
    }
}

+ (NSString *)numOfATimerToNow:(NSString *)timer{
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:[timer intValue]];
    NSDate *nowDate=[NSDate date];
    NSTimeInterval time=[nowDate timeIntervalSinceDate:date];
    if (time/3600<24&&(time/3600)>=1) {
        return [NSString stringWithFormat:@"%d小时",(int)time/3600];
    }else if(time/3600<1){
        return [NSString stringWithFormat:@"%d分钟",(int)time/60];
    }else{
        return [NSString stringWithFormat:@"%d天",(int)time/(3600*24)];
    }

}

+ (NSString *)getTimeStrWithOldDateFomatter:(NSString *)oldFormatterStyle DateStr:(NSString *)date newFormatter:(NSString *)newFormatter{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:oldFormatterStyle];
    NSString *timeStr=@"";
    NSDate *time=[formatter dateFromString:date];
    [formatter setDateFormat:newFormatter];
    timeStr=[formatter stringFromDate:time];

    return timeStr;

}

#pragma mark -获取若干天前后的日期
+ (NSString *)getEndDateStrWithDays:(CGFloat)days isBefore:(BOOL)isBefore{
    NSDateFormatter *formatter=[NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *theDate = nil;
    if (isBefore) {
        theDate=[NSDate dateWithTimeInterval:-60*60*24*days sinceDate:[NSDate date]];
    }else{
        theDate=[NSDate dateWithTimeInterval:60*60*24*days sinceDate:[NSDate date]];
    }
    NSString *endStr=[formatter stringFromDate:theDate];
    return endStr;
}

+ (NSString *)getDayToday {
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    return [formatter stringFromDate:[NSDate date]];
}

// 获取当前周的周一和周日的时间
+ (NSString *)getFirstWeekTime
{
    NSDate *nowDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitCalendar fromDate:nowDate];
    // 获取今天是周几
    NSInteger weekDay = [comp weekday];
    // 获取几天是几号
    NSInteger day = [comp day];
    
    // 计算当前日期和本周的星期一和星期天相差天数
    long firstDiff,lastDiff;
    //    weekDay = 1;
    if (weekDay == 1)
    {
        firstDiff = -6;
        lastDiff = 0;
    }
    else
    {
        firstDiff = [calendar firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    NSLog(@"firstDiff: %ld   lastDiff: %ld",firstDiff,lastDiff);
    
    // 在当前日期(去掉时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay   fromDate:nowDate];
    [lastDayComp setDay:day + lastDiff];
    //NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];
    
    return firstDay;
    
}

//获取当月第一天日期
+ (NSString *)getFirstDayInMonth{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    return [dateStr stringByAppendingString:@"01"];
}

//获取当月最后一天日期
+ (NSString *)getLastDayInMonth{
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
    //获取当月的天数
    NSUInteger numberOfDaysInMonth = range.length;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    return [dateStr stringByAppendingString:[NSString stringWithFormat:@"%ld",numberOfDaysInMonth]];
}

//获取上月第一天日期
+ (NSString *)getFirstDayInLastMonth{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    NSInteger month=[dateArr[1] integerValue];
    month--;
    //计算上一个月
    if (month==0) {
        month=12;
        year--;
    }
    //上一个月字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-%ld-",year,month];
    
    return [newMonth stringByAppendingString:@"01"];
}

//获取上月最后一天日期
+ (NSString *)getLastDayInLastMonth{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    NSInteger month=[dateArr[1] integerValue];
    month--;
    //计算上一个月
    if (month==0) {
        month=12;
        year--;
    }
    //上一个月字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-%ld",year,month];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[formatter dateFromString:newMonth]];
    //上一个月的天数
    NSUInteger numberOfDaysInMonth = range.length;
    return [newMonth stringByAppendingString:[NSString stringWithFormat:@"-%ld",numberOfDaysInMonth]];
}

//获取本季度第一天日期
+ (NSString *)getFirstDayWithQuarter{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    NSInteger month=[dateArr[1] integerValue];
    //根据月份判断季度第一天
    if (month==1||month==2||month==3) {
        month=1;
    }else if (month==4||month==5||month==6){
        month=4;
    }else if (month==7||month==8||month==9){
        month=7;
    }else{
        month=10;
    }
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-%ld-01",year,month];
    
    return newMonth;
}

//获取本季度最后一天日期
+ (NSString *)getLastDayWithQuarter{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    NSInteger month=[dateArr[1] integerValue];
    NSInteger day=0;
    //根据月份判断季度最后一天
    if (month==1||month==2||month==3) {
        month=3;
        day=31;
    }else if (month==4||month==5||month==6){
        month=6;
        day=30;
    }else if (month==7||month==8||month==9){
        month=9;
        day=30;
    }else{
        month=12;
        day=31;
    }
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day];
    
    return newMonth;
}

//获取上季度第一天日期
+ (NSString *)getFirstDayWithLastQuarter{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    NSInteger month=[dateArr[1] integerValue];
    //根据月份判断季度第一天
    if (month==1||month==2||month==3) {
        month=1;
    }else if (month==4||month==5||month==6){
        month=4;
    }else if (month==7||month==8||month==9){
        month=7;
    }else{
        month=10;
    }
    //因为是上一季度所以要减3个月
    month-=3;
    //在判断一次 如果月份为负值 则为上一年的最后一个月
    if (month<0) {
        month=10;
        year--;
    }
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-%ld-01",year,month];
    
    return newMonth;
}

//获取上季度最后一天日期
+ (NSString *)getLastDayWithLastQuarter{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    NSInteger month=[dateArr[1] integerValue];
    NSInteger day=0;
    //根据月份判断季度第一天
    if (month==1||month==2||month==3) {
        month=1;
    }else if (month==4||month==5||month==6){
        month=4;
    }else if (month==7||month==8||month==9){
        month=7;
    }else{
        month=10;
    }
    //因为是上一季度所以要减3个月
    month-=3;
    //在判断一次 如果月份为负值 则为上一年的最后一个季度
    if (month<0) {
        month=10;
        year--;
    }
    //拿到月份之后要判断该月有多少天
    if (month==1||month==7||month==10) {
        day=31;
    }else{
        day=30;
    }
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day];
    
    return newMonth;
}

//获取上半年第一天日期
+ (NSString *)getFirstDayWithFirstHalfAYear{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-01-01",year];
    
    return newMonth;
}

//获取上半年最后一天日期
+ (NSString *)getLastDayWithFirstHalfAYear{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-06-30",year];
    
    return newMonth;
}

//获取下半年第一天日期
+ (NSString *)getFirstDayWithSecondHalfAYear{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-07-01",year];
    
    return newMonth;
}

//获取下半年最后一天日期
+ (NSString *)getLastDayWithSecondHalfAYear{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-12-31",year];
    
    return newMonth;
}

//获取上下半年最后一天日期
+ (NSString *)getLastDayWithHalfAYear{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateStr=[formatter stringFromDate:[NSDate date]];
    //切割
    NSArray *dateArr=[dateStr componentsSeparatedByString:@"-"];
    NSInteger year=[dateArr[0] integerValue];
    NSInteger month=[dateArr[1] integerValue];
    NSInteger day=0;
    //根据月份判断第一天
    if (month>=1&&month<=6) {
        month=1;
        day=31;
    }else{
        month=7;
        day=31;
    }
    //拼接字符串
    NSString *newMonth=[NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day];
    
    return newMonth;
}

// 获取当前周的周一和周日的时间
+ (NSString *)getLastWeekTime
{
    NSDate *nowDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitCalendar fromDate:nowDate];
    // 获取今天是周几
    NSInteger weekDay = [comp weekday];
    // 获取几天是几号
    NSInteger day = [comp day];
    
    // 计算当前日期和本周的星期一和星期天相差天数
    long firstDiff,lastDiff;
    //    weekDay = 1;
    if (weekDay == 1)
    {
        firstDiff = -6;
        lastDiff = 0;
    }
    else
    {
        firstDiff = [calendar firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    NSLog(@"firstDiff: %ld   lastDiff: %ld",firstDiff,lastDiff);
    
    // 在当前日期(去掉时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];
    [firstDayComp setDay:day + firstDiff];
    //NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay   fromDate:nowDate];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
   // NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];
    NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];
    //NSLog(@"%@=======%@",firstDay,lastDay);
    
    //NSString *dateStr = [NSString stringWithFormat:@"%@-%@",firstDay,lastDay];
    
    return lastDay;
    
}

+ (NSString *)getDaysWithBeginTime:(NSString *)beginStr endTime:(NSString *)endStr{
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

    NSDate *date1=[dateFormatter dateFromString:beginStr];
    NSDate *date2=[dateFormatter dateFromString:endStr];

    //取两个日期对象的时间间隔：
    //这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:typedef double NSTimeInterval;
    NSTimeInterval time=[date1 timeIntervalSinceDate:date2];
    if (time/3600<24&&(time/3600)>=1) {
        return [NSString stringWithFormat:@"%d小时",(int)time/3600];
    }else if(time/3600<1){
        return [NSString stringWithFormat:@"%d分钟",(int)time/60];
    }else{
        return [NSString stringWithFormat:@"%d天",(int)time/(3600*24)];
    }
}

+ (void)postAlertViewControllerWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitle:(NSString *)otherButtonTitle cancelEvent:(void (^)())cancelBlock otherEvent:(void (^)())otherBlock viewController:(id)viewController{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction=nil;
    UIAlertAction *otherAction=nil;
    if (cancelButtonTitle) {
        cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
                        {
                            //cancel Button
                            if (cancelBlock) {
                                cancelBlock();
                            }
                        }];
            [alertController addAction:cancelAction];
    }
    if (otherButtonTitle) {
        otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
                       {
                           if (otherBlock) {
                               otherBlock();
                           }
                       }];
        [alertController addAction:otherAction];
    }
    
    [viewController presentViewController:alertController animated:YES completion:nil];
}

+ (BOOL)isEmpty:(NSString *) str {
    
    if (!str) {
        return YES;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return YES;
        } else {
            return NO;
        }
    }
}

+ (CGFloat  )totalDiskSpace

{
    
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    NSNumber *number=[fattributes objectForKey:NSFileSystemSize];
    return [number doubleValue]/1024/1024/1024;
    
}

+ (CGFloat )freeDiskSpace

{
    
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    NSNumber *number=[fattributes objectForKey:NSFileSystemFreeSize];
    
    return [number doubleValue]/1024/1024/1024;
    
}
////可用内存
//+(double)availableMemory
//{
//    vm_statistics_data_t vmStats;
//    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
//    kern_return_t kernReturn = host_statistics(mach_host_self(),
//                                               HOST_VM_INFO,
//                                               (host_info_t)&vmStats,
//                                               &infoCount);
//    
//    if (kernReturn != KERN_SUCCESS) {
//        return NSNotFound;
//    }
//    
//    return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0;
//}
////已使用内存
//+(double)usedMemory
//{
//    task_basic_info_data_t taskInfo;
//    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
//    kern_return_t kernReturn = task_info(mach_task_self(),
//                                         TASK_BASIC_INFO,
//                                         (task_info_t)&taskInfo,
//                                         &infoCount);
//    
//    if (kernReturn != KERN_SUCCESS
//        ) {
//        return NSNotFound;
//    }
//    
//    return taskInfo.resident_size / 1024.0 / 1024.0;
//}

//- (NSString *)getFilePath:(NSString *)URL {
//    //获取沙盒中/Library/Caches
//    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//    //拼接图片文件的绝对路径/xxx/xxx/Library/Caches/
//    NSString *filePath = [cachesPath stringByAppendingPathComponent:[URL lastPathComponent]];
//    
//    return filePath;
//}

+ (UIColor *) HexColorToRedGreenBlue:(NSString *)hexColorString
{
    NSString *cString = [[hexColorString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return nil;
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return nil;
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int red, green, blue;
    [[NSScanner scannerWithString:rString] scanHexInt:&red];
    [[NSScanner scannerWithString:gString] scanHexInt:&green];
    [[NSScanner scannerWithString:bString] scanHexInt:&blue];
    
    return [UIColor colorWithRed:((float) red / 255.0f) green:((float) green / 255.0f) blue:((float) blue / 255.0f) alpha:1.0f];
}

+ (void)postLoadViewWithText:(NSString *)message View:(UIView *)view{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.removeFromSuperViewOnHide =YES;
    hud.labelText = message;
    hud.minSize =CGSizeMake(80.f,10.0f);
    //[hud hide:YES afterDelay:1];
}

+ (void)postMessageWithText:(NSString *)message View:(UIView *)view{
    MBProgressHUD* progress_hud1 = [MBProgressHUD showHUDAddedTo:view animated:YES];
    progress_hud1.mode = MBProgressHUDModeCustomView;
    progress_hud1.labelText = NSLocalizedString(message, nil);
    progress_hud1.customView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mark_no"]];
    
    
    [progress_hud1 showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [progress_hud1 removeFromSuperview];
    }];
}

+ (void)hideLoadViewWithView:(UIView *)view{
    if([MBProgressHUD hideAllHUDsForView:view animated:YES]>0){
        //NSLog(@"加载框移除失败");
    };
}

+ (void)postDetailMessageWithText:(NSString *)message View:(UIView *)view{
    MBProgressHUD* progress_hud1 = [MBProgressHUD showHUDAddedTo:view animated:YES];
    progress_hud1.mode = MBProgressHUDModeCustomView;
    progress_hud1.detailsLabelText = NSLocalizedString(message, nil);
    progress_hud1.customView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mark_no"]];
    
    
    [progress_hud1 showAnimated:YES whileExecutingBlock:^{
        sleep(2);
    } completionBlock:^{
        [progress_hud1 removeFromSuperview];
    }];
}

+ (NSString *)timeWithDate:(NSDate *)date
{
    if (date == nil)
    {
        return @"";
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone localTimeZone];
    formatter.timeStyle = NSDateFormatterShortStyle;
    formatter.dateStyle = NSDateFormatterMediumStyle;
    formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    
    NSDate *now = [NSDate date];
    
    NSCalendarUnit unit = NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday;
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *components = [calendar components:unit fromDate:now];
    NSInteger nowHour = components.hour;
    NSInteger nowMinute = components.minute;
    NSInteger nowSecond = components.second;
    NSInteger nowWeekday = components.weekday;
    
    components = [calendar components:unit fromDate:date];
    NSInteger dateHour = components.hour;
    NSInteger dateMinute = components.minute;
    NSInteger dateWeekday = components.weekday;
    
    NSTimeInterval interval = [now timeIntervalSinceDate:date];
    
    NSString *result = @"";
    if (interval > 24*60*60*7)
    {
        //一个星期之前显示全部时间
        result = [formatter stringFromDate:date];
    }
    else if(interval >= 24*60*60*1+nowHour*60*60+nowMinute*60+nowSecond)//大于等于2天
    {
        //上个星期
        if(nowWeekday<dateWeekday)
        {
            result = [formatter stringFromDate:date];
        }
        else    //本星期要显示星期
        {
            result = [NSString stringWithFormat:@"%@ %02zi:%02zi", [self stringedWeekday:dateWeekday], dateHour, dateMinute];
        }
    }
    else if(interval >= nowHour*60*60+nowMinute*60+nowSecond)    //昨天
    {
        result = [NSString stringWithFormat:@"%@ %02zi:%02zi", @"昨天", dateHour, dateMinute];
    }
    else
    {
        result = [NSString stringWithFormat:@"%02zi:%02zi", dateHour, dateMinute];
    }
    
    return result;
}

+ (NSString *)stringedWeekday:(NSUInteger)weekday
{
    assert(weekday>=1 && weekday<=7);
    
    return @[@"星期日",
             @"星期一",
             @"星期二",
             @"星期三",
             @"星期四",
             @"星期五",
             @"星期六"][weekday-1];
}

//获取IP
+ (NSString *)getIPStr{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"IP"];
}
//获取端口号
+ (NSString *)getPortStr{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"Port"];
}

+ (NSString *)getServerURL{
    return [NSString stringWithFormat:@"http://%@:%@/PhoneService.asmx",[[NSUserDefaults standardUserDefaults]objectForKey:@"IP"],[[NSUserDefaults standardUserDefaults]objectForKey:@"Port"]];
}


+ (NSString *)getUuidWithKeyChain {
    NSString *strUUID = [SSKeychain passwordForService:@"com.LNjujin.MobileOffice"account:@"user"];
    if (strUUID == nil || [strUUID isEqualToString:@""])
    {
        CFUUIDRef uuid = CFUUIDCreate( nil );
        CFStringRef uuidString = CFUUIDCreateString( nil, uuid );
        NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
        CFRelease(uuid);
        CFRelease(uuidString);
        [SSKeychain setPassword:strUUID
                     forService:@"com.LNjujin.MobileOffice"account:@"user"];
        return result;
    }else{
        return strUUID;
    }
}

//根据componentsStr切割string
+ (NSArray *)getArrWithStr:(NSString *)string componentsStr:(NSString *)componentsStr{
    //去掉前面的|
    if ([[string substringToIndex:1]isEqualToString:componentsStr]) {
        string=[string substringFromIndex:1];
    }
    //去掉最后面的|
    if ([[string substringFromIndex:string.length-1]isEqualToString:componentsStr]) {
        string =[string substringToIndex:string.length-1];
    }
    NSArray *infoArr=[string componentsSeparatedByString:componentsStr];
    return infoArr;
}

+ (NSString *)getUserType{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"userType"];
}

+ (NSString *)getSessionID{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"sessionId"];
}

+ (NSString *)getUserName{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"empName"];
}

+ (NSString *)getUserDepartName{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"departName"];
}
+(NSString *)getDepartId{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"departId"];
}
+(NSString *)getPostID{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"postId"];
}
+(NSString *)getPostName{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"postName"];
}
+(NSString *)getIdentityFlag{
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"identityFlag"];
}

@end


